/*
 * @(#)org.example.netty.heartbeat 2020/4/2/0002
 *
 * Copy Right@ 人人译视界
 */


package org.example.netty.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.example.netty.groupchat.GroupChatServerHandler;

import java.util.concurrent.TimeUnit;

/**
 * <pre>
 * @author tuwei
 *
 * @version 0.9
 *
 * 修改版本: 0.9
 * 修改日期: 2020/4/2/0002
 * 修改人 :  tuwei
 * 修改说明: 初步完成
 * 复审人 ：
 * </pre>
 */
public class MyServer {
	public static void main(String[] args) throws InterruptedException {
		NioEventLoopGroup boss = new NioEventLoopGroup(1);
		NioEventLoopGroup worker = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(boss, worker)
					.channel(NioServerSocketChannel.class)
					.handler(new LoggingHandler(LogLevel.INFO))// 日志处理器
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel socketChannel) throws Exception {
							ChannelPipeline pipeline = socketChannel.pipeline();
							/**
							 * IdleStateHandler是netty提供的处理空闲状态的处理器
							 * 参数说明：
							 * readerIdleTime——多久没有读取数据，就会发送一个心跳检测包检测是否还是连接状态
							 * writerIdleTime——多久没有写数据，就会发送一个心跳检测包检测是否还是连接状态
							 * allIdleTime——多久既没有读也没有写操作，就会发送一个心跳检测包
							 *
							 * 触发IdleStateEvent事件后，会传递给管道的下一个handler的userEventTriggered方法
							 */
							pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));
							pipeline.addLast(new MyServerHandler());
						}
					});
			System.out.println("netty服务器启动");
			ChannelFuture sync = bootstrap.bind(7000).sync();
			sync.channel().closeFuture().sync();
		} finally {
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
}
